package org.ccpp.portal.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class SQLConexion {

	private Connection conn;
	private Statement stmt;
	private boolean conectado=false; 
	public static boolean modo_test=false;
	
	public void conectar() throws Exception{
		conectar(false);
	}
	
	public void conectar(boolean updatable) throws Exception{
		if (!modo_test){
			Context initContext = new InitialContext();
			Context envContext  = (Context)initContext.lookup("java:/comp/env");
			DataSource ds = (DataSource)envContext.lookup("jdbc/ccpp");
			conn = ds.getConnection();
		}else{
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jorgerubira_ccpp?user=ccpp&password=cp2010");
		}
		if (updatable){
			stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		}else{
			stmt = conn.createStatement();
		}
		conectado=true;
	}
	
	public void desconectar(){
		conectado=false;
		try{ 
			stmt.close(); 
		}catch(Exception e){}
		try{ 
			conn.close(); 
		}catch(Exception e){}
	}

	public Statement getStatement(){
		return stmt;
	}
	
	public boolean estaConectado() throws Exception{
		return conectado;
	}
}
